package org.csu.onlineedubackend.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.onlineedubackend.dto.PendingAssignmentDTO;
import org.csu.onlineedubackend.entity.StudentAnswer;
import org.csu.onlineedubackend.mapper.StudentAnswerMapper;
import org.csu.onlineedubackend.service.StudentAnswerService;
import org.springframework.stereotype.Service;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.csu.onlineedubackend.mapper.CourseSubscribeMapper;
import org.csu.onlineedubackend.mapper.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class StudentAnswerServiceImpl extends ServiceImpl<StudentAnswerMapper, StudentAnswer> implements StudentAnswerService {

    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private CourseSubscribeMapper courseSubscribeMapper;

    @Autowired
    private StudentAnswerMapper studentAnswerMapper;

    @Override
    public StudentAnswer submitAnswer(StudentAnswer answer) {
        // 始终创建新记录，保留历史提交
        answer.setId(null); // 确保不会更新现有记录
            baseMapper.insert(answer);
        return answer;
    }

    @Override
    public StudentAnswer getAnswerByQuestionAndStudent(Integer questionId, Integer studentId) {
        QueryWrapper<StudentAnswer> wrapper = new QueryWrapper<>();
        wrapper.eq("question_id", questionId)
               .eq("student_id", studentId)
               .orderByDesc("answered_at")
               .last("LIMIT 1"); // 只获取最新的一条记录
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public List<StudentAnswer> getAnswersByQuestionId(Integer questionId) {
        QueryWrapper<StudentAnswer> wrapper = new QueryWrapper<>();
        wrapper.eq("question_id", questionId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<StudentAnswer> getAnswersByStudentId(Integer studentId) {
        QueryWrapper<StudentAnswer> wrapper = new QueryWrapper<>();
        wrapper.eq("student_id", studentId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public boolean markAnswer(Integer answerId, boolean isCorrect) {
        StudentAnswer answer = baseMapper.selectById(answerId);
        if (answer == null) return false;
        answer.setIsCorrect(isCorrect);
        return baseMapper.updateById(answer) > 0;
    }
    
    @Override
    public boolean scoreAnswer(Integer answerId, Double score) {
        StudentAnswer answer = baseMapper.selectById(answerId);
        if (answer == null) return false;
        answer.setScore(score);
        return baseMapper.updateById(answer) > 0;
    }

    @Override
    public StudentAnswer getById(Integer answerId) {
        return baseMapper.selectById(answerId);
    }

    @Override
    public boolean deleteAnswer(Integer answerId) {
        return baseMapper.deleteById(answerId) > 0;
    }

    @Override
    public List<StudentAnswer> getAnswersByCourseId(Integer courseId) {
        // 需要通過 Question 表關聯查詢
        // 這裡需要擴展 Mapper 來支持聯表查詢
        // 暫時返回空列表，需要實現相關邏輯
        return new java.util.ArrayList<>();
    }

    @Override
    public List<StudentAnswer> getAnswersByStudentAndCourse(Integer studentId, Integer courseId) {
        // 需要通過 Question 表關聯查詢
        // 這裡需要擴展 Mapper 來支持聯表查詢
        // 暫時返回空列表，需要實現相關邏輯
        return new java.util.ArrayList<>();
    }
    
    @Override
    public List<StudentAnswer> getHistoryAnswersByQuestionAndStudent(Integer questionId, Integer studentId) {
        // 使用mapper查詢歷史作業記錄，按照answeredAt降序排列
        QueryWrapper<StudentAnswer> wrapper = new QueryWrapper<>();
        wrapper.eq("question_id", questionId)
              .eq("student_id", studentId)
              .orderByDesc("answered_at");
        return baseMapper.selectList(wrapper);
    }
    
    @Override
    public int countDistinctStudentsByQuestionId(Integer questionId) {
        return baseMapper.countDistinctStudentsByQuestionId(questionId);
    }

    @Override
    public List<Object> getPendingAssignments(Long userId) {
        // 獲取學生訂閱的所有課程
        List<Map<String, Object>> subscribedCourses = courseSubscribeMapper.getSubscribedCoursesByUserId(userId);
        List<Map<String, Object>> pendingAssignments = new ArrayList<>();
        
        // 對每個課程，查詢未完成的作業
        for (Map<String, Object> course : subscribedCourses) {
            Long courseId = ((Number) course.get("id")).longValue();
            String courseName = (String) course.get("name");
            
//            // 獲取課程的所有作業
//            List<Map<String, Object>> questions = questionMapper.getQuestionsByCourseId(courseId);
//
//            for (Map<String, Object> question : questions) {
//                Long questionId = ((Number) question.get("id")).longValue();
//
//                // 檢查學生是否已完成此作業
//                Integer count = baseMapper.countByUserIdAndQuestionId(userId.intValue(), questionId.intValue());
//
//                // 如果未完成，則添加到待辦列表
//                if (count == 0) {
//                    Map<String, Object> assignment = new HashMap<>();
//                    assignment.put("questionId", questionId);
//                    assignment.put("title", question.get("title"));
//                    assignment.put("content", question.get("content"));
//                    assignment.put("deadline", question.get("deadline"));
//                    assignment.put("courseId", courseId);
//                    assignment.put("courseName", courseName);
//
//                    pendingAssignments.add(assignment);
//                }
//            }
            // 获取课程的所有作业（只查当前课程下的题目）
            List<Map<String, Object>> questions = questionMapper.getQuestionsByCourseId(courseId);

            for (Map<String, Object> question : questions) {
                Long questionId = ((Number) question.get("id")).longValue();

                // 检查学生是否已完成此作业
                Integer count = baseMapper.countByUserIdAndQuestionId(userId.intValue(), questionId.intValue());

                // 如果未完成，则添加到待办列表
                if (count == 0) {
                    Map<String, Object> assignment = new HashMap<>();
                    assignment.put("questionId", questionId);
                    assignment.put("title", question.get("title"));
                    assignment.put("content", question.get("content"));
                    assignment.put("deadline", question.get("deadline"));
                    assignment.put("courseId", courseId); // 这里用循环外层的courseId即可
                    assignment.put("courseName", courseName);

                    pendingAssignments.add(assignment);
                }
            }
        }
        
        // 按截止日期排序
        pendingAssignments.sort((a, b) -> {
            Date deadlineA = (Date) a.get("deadline");
            Date deadlineB = (Date) b.get("deadline");
            
            if (deadlineA == null && deadlineB == null) return 0;
            if (deadlineA == null) return 1;
            if (deadlineB == null) return -1;
            
            return deadlineA.compareTo(deadlineB);
        });
        
        return new ArrayList<>(pendingAssignments);
    }

    @Override
    public List<PendingAssignmentDTO> getPendingAssignmentsByTeacher(Integer teacherId, Integer limit) {
        List<PendingAssignmentDTO> all = studentAnswerMapper.selectPendingAssignmentsByTeacher(teacherId);
        if (limit != null && all.size() > limit) {
            return all.subList(0, limit);
        }
        return all;
    }
}